#ifndef USER_CLASS_HPP
#define USER_CLASS_HPP

#define MAX_USERNAME_LENGTH 8
#define MAX_PASSWORD_LENGTH 8

#include "env.h"
#include "messageStruct.h"
#include <iostream>
#include <cstring>
#include <fstream>
#include <limits>

using namespace std;


struct userInfo {
  char username[MAX_USERNAME_LENGTH] = {0};
  char separate[1] = {0}; // 分隔符
  char password[MAX_PASSWORD_LENGTH] = {0};
};

userInfo inputUserInfo() {
  struct userInfo temp;
  cout << "Please enter username: (no more than 8 char)" << endl;
  cin.get(temp.username, 9);
  cout << "Please enter password: (no more than 8 char)" << endl;
  cin.clear();
  cin.ignore((std::numeric_limits<streamsize>::max)(), '\n'); // 清空缓冲区
  cin.get(temp.password, 9);
  cin.clear();
  cin.ignore((std::numeric_limits<streamsize>::max)(), '\n'); // 清空缓冲区
  return temp;
}

class USERMODEL {
  public:
    USERMODEL() {
      FILE* p = fopen(USER_FILE, "a+");
      fseek(p, 0, SEEK_END);
      int length = ftell(p);
      len_ = length / sizeof(userInfo);
      fseek(p, 0, SEEK_SET);
      users_ = new userInfo[len_];
      fread(users_, sizeof(userInfo), len_, p);
      fclose(p);
    }
    ~USERMODEL() {
      delete users_;
    }
    // 用于调试
    void printAll() {
      for (int i = 0; i < len_; i++) print_(users_[i]);
    }
    int find(char username[8]) {
      for (int i = 0; i < len_; i++) {
        print_(users_[i]);
        if(strcmp(users_[i].username, username) == 0) { return i; }
      }
      return -1;
    }
    // 用于验证登陆
    // 验证成功：SUCCESS(200)
    // 账户名不存在：NOTFOUND(404)
    // 找到用户名但是密码错误：NOTFOUND(401)
    StatusType login(char username[8], char password[8]) {
      int index = find(username);
      if (index != -1) {
        cout << users_[index].password << endl;
        cout << password << '\n' << endl;
        if (strcmp(users_[index].password, password) == 0) return SUCCESS;
        else return PASSWORDERROR;
      };
      return NOTFOUND;
    }
    int reg() {
      struct userInfo temp = inputUserInfo();

      cout << "username: " << temp.username << endl;
      cout << "password: " << temp.password << endl;
      

      // 写入文件
      FILE* p = fopen(USER_FILE, "a+");
      if(p == NULL) {return 0;};
      fwrite(&temp, sizeof(temp), 1 , p);
      fclose(p);
      return 1;
    };
  private:
    struct userInfo* users_;
    int len_;
    void print_(struct userInfo user) {
      cout << "username: " << user.username
        << " password: " << user.password 
        << "\n" << endl;
    }
};
#endif // USER_CLASS_HPP